package com.luoy.netty.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.net.InetSocketAddress;

/**
 * netty客户端
 *
 * @author LUOYUAN
 * @create 2019-07-08-11:41
 */
public class EchoClient {

    private final int port;

    private  final  String host;

    public EchoClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public void start() throws InterruptedException{
        //线程组
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            // 客户端启动必备
            Bootstrap bootstrap = new Bootstrap();

            //
            bootstrap.group(group)
                     .channel(NioSocketChannel.class)//指名用NIO进行网络通讯
                     .remoteAddress(new InetSocketAddress(host,port)) //配置远程服务器的地址
                     .handler(new EchoClientHandler());
            //连接到远程节点，阻塞等待直到连接完成
            ChannelFuture f = bootstrap.connect().sync();
            //阻塞，直到channel关闭
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException{
        new EchoClient(6789,"127.0.0.1").start();
    }
}
